#   Copyright 2006 Jerome Lacoste (jerome@coffeebreaks.org)
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
# Filters added to this controller will be run for all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base

  # http://www.railsweenie.com/forums/1/topics/314?page=1
  # because pagination requires an id and cannot take into account the @instance.has_many_relation as parameter
  # we have to implement our pagination
  # warning: may be a performance drawback if many items!!
  def pagination(items, options={})
    page = (options[:page] || 1).to_i
    items_per_page = options[:per_page] || 10
    offset = (page - 1) * items_per_page

    @item_pages = Paginator.new(self, items.length, items_per_page, page)
    @items = items[offset..(offset + items_per_page - 1)]
    return @item_pages, @items
  end

  def authorize
    if session[:user_id].nil?
      session[:jumpto] = request.parameters
      # FIXME cache results ??
      if User.find(:all).size == 0
        flash[:notice] = "Please create the first user of the system, the one with administrative rights"
        redirect_to(:controller => "login", :action => "add_user")
      else
        flash[:notice] = "Please log in"
        redirect_to(:controller => "login", :action => "login")
      end
    end
  end

  def authorize_add_user
    if session[:user_id].nil?
      # FIXME cache results ??
      unless User.find(:all).size == 0
        flash[:notice] = "Please log in"
        redirect_to(:controller => "login", :action => "login")
      end
    end
  end
  private
  def redirect_to_index(msg = nil)
    flash[:notice] = msg if msg
    redirect_to(:action => 'index')    
  end

end
